from ninja import Router, Schema, Field
from django.utils import timezone

from apps.commom.water_droplets import WaterDropletsTaskSerializer
from apps.schemas import R
from models.models import WaterDropletsTask
from utils.auth import ManagerAuthBearer
from utils.decorators import handle_exception

water_droplets_router = Router(tags=["水滴获取任务管理"], auth=ManagerAuthBearer())


class WaterDropletsTaskUpdateSchema(Schema):
    on: bool = Field(default=False, description="是否开启")
    droplet_number: int = Field(default=0, description="水滴数量")


@water_droplets_router.get("/water_drop_tasks", summary="获取水滴任务列表")
@handle_exception("获取水滴任务列表失败")
def get_water_drop_tasks(request):
    tasks = WaterDropletsTask.objects.all()
    return R.ok(data=WaterDropletsTaskSerializer(tasks, many=True).data)


@water_droplets_router.get("/water_drop_task/{task_id}", summary="获取水滴获取任务详情")
@handle_exception("获取水滴获取任务详情失败")
def get_water_drop_task(request, task_id: int):
    task = WaterDropletsTask.objects.get(id=task_id)
    return R.ok(data=WaterDropletsTaskSerializer(task).data)


@water_droplets_router.put("/water_drop_task/{task_id}", summary="水滴获取任务设置")
@handle_exception("水滴获取任务设置失败")
def set_water_drop_tasks(request, task_id: int, data: WaterDropletsTaskUpdateSchema):
    task = WaterDropletsTask.objects.get(id=task_id)
    task.on = data.on
    task.droplet_number = data.droplet_number
    task.set_time = timezone.now()
    task.save()
    return R.ok(msg="设置成功")
